package com.example.docking.service.impl;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.response.MeasureUnitData;
import com.example.docking.dao.jindie.response.SaveData;
import com.example.docking.service.MeasureUnitService;
import com.example.docking.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MeasureUnitServiceImpl implements MeasureUnitService {
    private static final Logger logger = LoggerFactory.getLogger(MeasureUnitServiceImpl.class);

    @Override
    public String getMeasureUnitId(DataServiceImpl service, String unit) throws Exception {
        Gson gson = new Gson();
        ResponseData<SaveData> responseData = new ResponseData<>();
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        String unit_id = "";
        ApiResult materialResult1 = null;
        ApiResult MeasureUnitDataResult = null;

        // 调用分页查询方法获取计量单位数据
        MeasureUnitDataResult = service.SelectDataDetail(Constants.MEASURE_UNIT, map, "");
        Type MeasureUnitDataType = new TypeToken<ResponseData<GenericDataItem<MeasureUnitData>>>() {
        }.getType();
        ResponseData<GenericDataItem<MeasureUnitData>> response = gson.fromJson(MeasureUnitDataResult.getBody(), MeasureUnitDataType);
        GenericDataItem<MeasureUnitData> genericDataItem = response.getData();
        // 解析分页信息
        String count = genericDataItem.getCount();
        int countNum = Integer.valueOf(count);
        int Pagesum = pageSize;
        List<MeasureUnitData> measureUnitData = genericDataItem.getRows();

        List<MeasureUnitData> allMeasureUnitData = new ArrayList<>(measureUnitData);
        // 如果不是最后一页，继续获取下一页数据
        while (Pagesum < countNum) {
            page++;
            map.put("page", String.valueOf(page));
            MeasureUnitDataResult = service.SelectDataDetail(Constants.MEASURE_UNIT, map, "");
            response = gson.fromJson(MeasureUnitDataResult.getBody(), MeasureUnitDataType);
            genericDataItem = response.getData();
            measureUnitData = genericDataItem.getRows();
            allMeasureUnitData.addAll(measureUnitData);
            Pagesum = pageSize * page;
        }

        boolean unitFound = false;
        for (MeasureUnitData measureUnitData1 : allMeasureUnitData) {
            if (measureUnitData1.getName().equals(unit)) {
                unit_id = measureUnitData1.getId();
                unitFound = true;
                break;
            }
        }
        //如果没有传值 默认给一个值
        if (unit.equals("") || unit == null) {
            unit_id = allMeasureUnitData.get(0).getId();
        } else {
            if (!unitFound) {
                // 否则新增InsertDataOne，materialDataRequest setBase_unit_id为返回值id
                MeasureUnitData measureUnit = new MeasureUnitData();
                measureUnit.setName(unit);
                measureUnit.setPrecision("0");//没做设置 默认赋值0
                materialResult1 = service.InsertDataOne(Constants.MEASURE_UNIT, map, measureUnit);
                Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
                }.getType();
                logger.info("插入计量单位" + unit);
                responseData = gson.fromJson(materialResult1.getBody(), SaveDataType);
                if (responseData.getErrcode() == 0) { // 假设0表示成功
                    SaveData saveData = responseData.getData();
                    unit_id = saveData.getIds().get(0);
                }
                logger.info("Code: " + responseData.getErrcode());
                logger.info("Message: " + responseData.getDescription());
                logger.info("data: " + responseData.getData());
            }
        }

        return unit_id;
    }

    public static void main(String[] args) throws Exception {
        MeasureUnitServiceImpl measureUnitService = new MeasureUnitServiceImpl();
        String str = measureUnitService.getMeasureUnitId(new DataServiceImpl(), "boxes");
        System.out.println(str);
    }
}